package com.zhangyx.spider.music;

import com.google.common.collect.Maps;
import com.zhangyx.comm.EncryptUtil;
import com.zhangyx.comm.RedisUtil;
import com.zhangyx.comm.SerializeUtils;
import com.zhangyx.comm.ThreadUtil;
import com.zhangyx.core.HttpClientUtil;
import com.zhangyx.core.Page;
import com.zhangyx.core.TaskManager;
import org.apache.commons.lang3.RandomStringUtils;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Config {

    //缓存
    public static final String song_page_requst = "song_page_requst";
    public static final String song_page_reponse = "song_page_reponse";
    public static final String user_page_requst = "user_page_requst";
    public static final String user_page_reponse = "user_page_reponse";
    public static final String repeat_prefix = "repeat_prefix";

    //请求信息

    //加密
    private final static String modulus = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7" +
            "b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280" +
            "104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932" +
            "575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b" +
            "3ece0462db0a22b8e7";
    private final static String nonce = "0CoJUm6Qyw8W8jud";
    private final static String pubKey = "010001";
    private static final String PARAMS = "params";
    private static final String ENCSECKEY = "encSecKey";

    public static Map<String, String> encrypt(String text) {
        String secKey = RandomStringUtils.random(16, "0123456789abcde");
        String encText = aesEncrypt(aesEncrypt(text, nonce), secKey);
        String encSecKey = rsaEncrypt(secKey, pubKey, modulus);

        Map<String, String> map = new HashMap<String, String>();
        map.put(PARAMS, encText);
        map.put(ENCSECKEY, encSecKey);
        return map;
    }

    private static String aesEncrypt(String text, String key) {
        try {
            IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(text.getBytes());

            return new BASE64Encoder().encode(encrypted);
        } catch (Exception e) {
            return "";
        }
    }

    private static String rsaEncrypt(String text, String exponent, String modulus) {
        text = new StringBuilder(text).reverse().toString();
        BigInteger rs = new BigInteger(String.format("%x", new BigInteger(1, text.getBytes())), 16)
                .modPow(new BigInteger(exponent, 16), new BigInteger(modulus, 16));
        String r = rs.toString(16);
        if (r.length() >= 256) {
            return r.substring(r.length() - 256, r.length());
        } else {
            while (r.length() < 256) {
                r = 0 + r;
            }
            return r;
        }
    }

    public static Map<String,String> getHeaders() {
        Map<String, String> headers = Maps.newHashMap();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
        return headers;
    }
    public static Map<String, String> getCookies() {
        Map<String, String> cookies = Maps.newHashMap();
        String prefix = String.valueOf(RandomStringUtils.random(5, "6lIfkhBfMe4uS2iVkt8Il2gS6IvDKnG5CiwiD"));
        cookies.put("JSESSIONID-WYYY", prefix + "hBfMe4uS2iVkt8Il2gS6IvDKnG5CiwiD%2FqbcWSgfq%5CJ2m%5C9SJ%2ByBWERaqeS5Z4EKCcfAmmt6%2B8gcuXEKTuXixFV7XGOXMgbV8Dlzt%2BI3%2FaVUYKHnulclpD9aYXjw82bvPWXAM8%2BeSwvXABJjPHcdAcf%2FMP5IQPk44dH7YylCju7%3A1504447414766");
        cookies.put(" _iuqxldmzr_", "32");
        //md5,当前时间
        String time = new Date().toString();
        cookies.put(" _ntes_nnid", EncryptUtil.getMD5(time) + "," + time);
        cookies.put(" _ntes_nuid", EncryptUtil.getMD5(time));
        return cookies;
    }

    public static Map<String, String> getCookiesForUser() {
        Map<String, String> cookies = Maps.newHashMap();
        //随机生成
        cookies.put("JSESSIONID-WYYY", "3DBGVKkDc9JNj8uNB0q3Yqn8FvuXoCXdXRvgKi1xhMXxybmV5H1wfvl8SGq2eJzlZDG3CWEDzJ1SJAn3GwK%5C2vkCF2x4wB7htupDJMdvyX7pJKqcxfB71RVJw29%2Bla5QeTClEo0v4uMCGzJ9%5CYR96w4IKMK%5CKPP1x9jBnwDwtjzXdfAn%3A1504425305025");
        cookies.put(" _iuqxldmzr_", "32");
        //md5,当前时间
        String time = new Date().toString();
        cookies.put(" _ntes_nnid", EncryptUtil.getMD5(time) + "," + time);
        cookies.put(" _ntes_nuid", EncryptUtil.getMD5(time));
        return cookies;
    }

    public static void main(String[] args){
        RedisUtil.init("127.0.0.1", 6379);
        HttpClientUtil.initPool(false);

        Map<String, String> entityStr = Config.encrypt("{\"rid\":\"R_SO_4_501133611\",\"offset\":\"60\",\"total\":\"false\",\"limit\":\"20\",\"csrf_token\":\"\"}");
        Page page = new Page();
        page.setUseGET(false);
        page.setUrl("http://music.163.com/weapi/v1/resource/comments/R_SO_4_495220123?csrf_token=");
        page.setRequestCookies(getCookies());
        page.setHeader(getHeaders());
        page.setEntity(entityStr);
        page.getTemp().put("song_id", "495220123");

        RedisUtil.pushStackObj(song_page_requst, page);
        ThreadUtil.sleepMills(1000);
        TaskManager.startTask(SongCrawler.class, 1);
        TaskManager.startTask(SongProcessor.class, 1);
        TaskManager.startTask(UserCrawler.class, 1);
        TaskManager.startTask(UserProcessor.class, 1);
    }

}